python中全组合函数(combinations)与全排列函数(permutations)的介绍与参数说明 |
您所在的位置:网站首页 › permutation python返回值 › python中全组合函数(combinations)与全排列函数(permutations)的介绍与参数说明 |
概要:在平常的编程过程中,往往需要面对排列组合的应用情况,而每次自己编写相应的函数会耗费较多的时间,而python中的itertools库就为我们解决了这个小问题。itertools库中的permutations函数可以输出可迭代对象的全排列情况,而combinations函数可以输出可迭代对象的全组合情况。 正文部分: print("祝大家每天快乐,love and peace!")1、全排列函数permutations() ①使用前准备: permutations函数作为itertools库中的函数,要使用它,自然首先要调用itertools库了。(python自带,不需自己另外安装) import itertools②语法说明: result=itertools.permutations(iterable,r), 其中result为对迭代对象处理之后返回的结果,数据类型为'itertools.permutations',如果需要的话,可以通过list()转化为列表。转化为列表之后的元素的数据类型为元组。元素默认排列顺序为迭代对象字典序上的从小到大(自行体会:>); iterable为需要排列的迭代对象,包括列表、字符串、元组、字典(只对键进行全排列); r为单个排列元素的长度,不修改的话,默认为迭代对象的元素个数。 ③实例演示: >>> a=[1,2,3] >>> result=itertools.permutations(a,2) >>> type(result) >>> list(result) [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] >>> result=list(result) >>> type(result[0]) >>> result=itertools.permutations(a) >>> list(result) [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]2、全组合函数combinations() ①使用前准备: 与permutations函数相同,不再赘述。(绝不是因为我懒,是的话我也不承认(手动狗头)) ②语法说明: result=itertools.combinations(iterable,r), 其中result为迭代对象处理之后返回的结果,数据类型为'itertools.combinations',如果需要的话,可以通过list()转化为列表。转化为列表之后的元素的数据类型为元组。元素默认排列顺序为按照迭代对象字典序上的从小到大; iterable为需要排列的迭代对象,包括列表、字符串、元组、字典(只对键进行全组合); r为单个排列元素的长度,必须修改,不然会报错(填一下吧,这个懒咱不偷)。 ③实例演示: >>> a=[1,2,3] >>> result=itertools.combinations(a,2) >>> type(result) >>> result=list(result) >>> result [(1, 2), (1, 3), (2, 3)] >>> type(result[0]) >>> result=list(itertools.combinations(a)) Traceback (most recent call last): File "", line 1, in result=list(itertools.combinations(a)) TypeError: combinations() missing required argument 'r' (pos 2) >>> result=list(itertools.combinations(a,3)) >>> result [(1, 2, 3)]结语:好了以上就是所有的内容,希望大家多多关注,点赞,收藏,这对我有很大的帮助。国康家安,大家下次再见喽!!!溜溜球~~
|
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |